// src/main/java/cn/edu/tju/elm/controller/wallet/TransactionController.java
package cn.edu.tju.elm.controller.wallet;

import cn.edu.tju.elm.model.dto.TransactionDTO;
import cn.edu.tju.elm.model.WalletTransaction;
import cn.edu.tju.elm.model.TransactionType;
import cn.edu.tju.elm.service.VirtualWalletService;
import cn.edu.tju.elm.service.WalletTransactionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/transactions")
@Tag(name = "transaction-controller", description = "交易记录查询接口")
public class TransactionController {

    @Autowired
    private VirtualWalletService walletService;

    @Autowired
    private WalletTransactionService transactionService;

    /**
     * 查询交易流水
     */
    @GetMapping("/history")
    @Operation(summary = "查询交易历史", description = "获取用户的交易历史记录")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "获取失败")
    })
    public ResponseEntity<List<TransactionDTO>> getTransactionHistory(
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId) {
        try {
            List<WalletTransaction> transactions = walletService.getTransactionHistory(userId);
            List<TransactionDTO> dtos = transactions.stream()
                    .map(this::convertToTransactionDTO)
                    .collect(Collectors.toList());
            return ResponseEntity.ok(dtos);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 根据时间范围查询交易流水
     */
    @GetMapping("/history/range")
    @Operation(summary = "按时间范围查询交易", description = "根据时间范围查询用户的交易记录")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "获取失败")
    })
    public ResponseEntity<List<TransactionDTO>> getTransactionHistoryByRange(
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId,
            @Parameter(description = "开始时间", required = true, example = "2023-01-01T00:00:00") 
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @Parameter(description = "结束时间", required = true, example = "2023-12-31T23:59:59") 
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        try {
            List<WalletTransaction> transactions = walletService.getTransactionHistoryByTimeRange(
                    userId, startTime, endTime);
            List<TransactionDTO> dtos = transactions.stream()
                    .map(this::convertToTransactionDTO)
                    .collect(Collectors.toList());
            return ResponseEntity.ok(dtos);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 根据交易类型查询
     */
    @GetMapping("/by-type")
    @Operation(summary = "按交易类型查询", description = "根据交易类型筛选用户的交易记录")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "获取失败")
    })
    public ResponseEntity<List<TransactionDTO>> getTransactionsByType(
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId,
            @Parameter(description = "交易类型", required = true) @RequestParam TransactionType transactionType) {
        try {
            // 先获取钱包ID
            var wallet = walletService.getWalletByUserId(userId);
            List<WalletTransaction> transactions = transactionService.getTransactionsByType(
                    wallet.getId(), transactionType);
            List<TransactionDTO> dtos = transactions.stream()
                    .map(this::convertToTransactionDTO)
                    .collect(Collectors.toList());
            return ResponseEntity.ok(dtos);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 查询交易详情
     */
    @GetMapping("/{transactionId}")
    @Operation(summary = "查询交易详情", description = "根据交易ID获取交易详情")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "获取失败"),
        @ApiResponse(responseCode = "404", description = "交易不存在")
    })
    public ResponseEntity<TransactionDTO> getTransactionDetail(
            @Parameter(description = "交易ID", required = true) @PathVariable Long transactionId) {
        try {
            WalletTransaction transaction = transactionService.getTransactionById(transactionId);
            return ResponseEntity.ok(convertToTransactionDTO(transaction));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 统计总收入
     */
    @GetMapping("/total-income")
    @Operation(summary = "统计总收入", description = "统计用户的总收入金额")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "获取失败")
    })
    public ResponseEntity<BigDecimal> getTotalIncome(
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId) {
        try {
            var wallet = walletService.getWalletByUserId(userId);
            BigDecimal totalIncome = transactionService.getTotalIncome(wallet.getId());
            return ResponseEntity.ok(totalIncome);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(BigDecimal.ZERO);
        }
    }

    /**
     * 统计总支出
     */
    @GetMapping("/total-expense")
    @Operation(summary = "统计总支出", description = "统计用户的总支出金额")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "获取失败")
    })
    public ResponseEntity<BigDecimal> getTotalExpense(
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId) {
        try {
            var wallet = walletService.getWalletByUserId(userId);
            BigDecimal totalExpense = transactionService.getTotalExpense(wallet.getId());
            return ResponseEntity.ok(totalExpense);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(BigDecimal.ZERO);
        }
    }

    // DTO转换方法
    private TransactionDTO convertToTransactionDTO(WalletTransaction transaction) {
        TransactionDTO dto = new TransactionDTO();
        dto.setId(transaction.getId());
        dto.setWalletId(transaction.getWalletId());
        dto.setTransactionType(transaction.getTransactionType());
        dto.setAmount(transaction.getAmount());
        dto.setBalanceBefore(transaction.getBalanceBefore());
        dto.setBalanceAfter(transaction.getBalanceAfter());
        dto.setDescription(transaction.getDescription());
        dto.setCreateTime(transaction.getCreateTime());
        dto.setReferenceId(transaction.getReferenceId());
        return dto;
    }
}